<template>
  <div class="login-container">
    <div class="login-bg">
      <!-- 背景方块装饰 -->
      <div class="square-box left-top"></div>
      <div class="square-box left-bottom"></div>
    </div>

    <div class="login-content">
      <!-- 左侧3D插图 -->
      <div class="login-left">
        <img src="@/assets/image/主体.png" alt="登录插图" />
      </div>

      <!-- 右侧登录表单 -->
      <div class="login-form-container">
        <div class="login-form-box">
          <h2 class="login-title">学生选课平台</h2>

          <el-form
            :model="loginForm"
            :rules="rules"
            ref="loginFormRef"
            class="login-form"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入学号或邮箱"
                prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input
                  v-model="loginForm.captcha"
                  placeholder="请输入验证码"
                  prefix-icon="Key"
                  class="captcha-input"
                />
                <div class="captcha-img" @click="refreshCaptcha">
                  <img :src="captchaImg" alt="验证码" />
                </div>
              </div>
            </el-form-item>

            <el-button
              type="primary"
              class="login-button"
              @click="handleLogin"
              :loading="loading"
            >
              登录
            </el-button>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 底部边框线 -->
    <div class="bottom-border"></div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { getCaptcha, checkCaptcha, login } from '@/api/user.js'
import { useUserStore } from '@/stores/user.js'
import { encryptByDES } from '@/utils/Encryption.js'
import { useRouteStore } from '@/stores/route.js'

// 获取用户store
const userStore = useUserStore()
// 获取路由
const router = useRouter()
// 获取路由store
const routeStore = useRouteStore()
// 登录表单引用，用于表单验证和提交
const loginFormRef = ref(null)
// 登录按钮加载状态
const loading = ref(false)
// 验证码图片URL
const captchaImg = ref('')

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
})

// 表单验证规则
const rules = {
  username: [{ required: true, message: '请输入学号或邮箱', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
}

/**
 * 刷新验证码
 */
const refreshCaptcha = async () => {
  try {
    const res = await getCaptcha()
    captchaImg.value = URL.createObjectURL(res)
  } catch (error) {
    console.error('获取验证码失败:', error)
    // 使用备用验证码图片
    captchaImg.value = '/assets/image/验证码示例.png'
  }
}

/**
 * 处理登录请求
 */
const handleLogin = () => {
  if (!loginFormRef.value) return

  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 开启加载
        loading.value = true
        // 校验验证码
        const { code, msg } = await checkCaptcha(loginForm.captcha)

        // 验证码错误处理
        if (code !== 200) {
          // 刷新验证码
          refreshCaptcha()
          return
        }
        // 加密密码
        loginForm.password = encryptByDES(loginForm.password)
        // 登录
        const res = await login(loginForm)
        if (res.code !== 200) {
          ElMessage.error(`登录失败：${res.msg}`)
          return
        } else {
          ElMessage.success('登录成功')

          // 初始化用户信息（包含检查登录状态和获取用户信息）
          await userStore.initInfo()

          // 确保动态路由已加载
          if (!routeStore.hasAddRoutes) {
            await routeStore.loadDynamicRoutes()
          }

          // 等待路由加载完成后再跳转
          setTimeout(() => {
            // 登录成功后，检查是否有重定向URL
            const redirect = router.currentRoute.value.query.redirect
            console.log('redirect', redirect)
            if (redirect) {
              // 如果有重定向URL，跳转到该URL
              console.log('跳转到重定向地址:', redirect)
              router.push(redirect)
            } else {
              // 没有重定向URL，默认跳转到首页
              console.log('跳转到首页')
              router.push('/home')
            }
          }, 100) // 减少延迟时间，因为我们已经确保路由加载完成
        }
      } catch (err) {
        console.error('登录过程发生错误:', err)
        ElMessage.error(`${err.message || '未知错误'}`)
        // 发生异常时刷新验证码
        refreshCaptcha()
      } finally {
        // 关闭加载
        loading.value = false
      }
    }
  })
}

// 页面加载时获取验证码
onMounted(() => {
  refreshCaptcha()
  // 回车添加事件
  window.addEventListener('keydown', (event) => {
    // 当用户按下回车键时触发登录
    if (event.key === 'Enter') {
      handleLogin()
    }
  })
})

// 卸载
onUnmounted(() => {
  // 移除回车绑定
  window.removeEventListener('keydown', handleLogin)
})
</script>

<style lang="less" scoped>
.login-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background: linear-gradient(to right bottom, #f0f8ff, #e1f0ff, #d2e8ff);
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.square-box {
  position: absolute;
  width: 180px;
  height: 180px;
  background-color: rgba(158, 207, 255, 0.2);
  border-radius: 10px;
  z-index: 1;
}

.left-top {
  top: 15%;
  left: 10%;
}

.left-bottom {
  bottom: 20%;
  left: 5%;
}

.login-content {
  display: flex;
  width: 80%;
  max-width: 1200px;
  height: 70%;
  z-index: 2;
  position: relative;
}

.login-left {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;

  img {
    width: 90%;
    max-width: 500px;
    object-fit: contain;
  }
}

.login-form-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-form-box {
  width: 380px;
  padding: 30px 40px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.login-title {
  font-size: 20px;
  text-align: center;
  margin-bottom: 30px;
  font-weight: 500;
  color: #333;
  font-weight: 600;
}

/* 角色选择 */
.role-switch {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  padding: 5px;
  background-color: #f5f7fa;
  border-radius: 30px;
  width: 220px;
  margin: 0 auto 25px;
}

.role-btn {
  padding: 8px 30px;
  text-align: center;
  cursor: pointer;
  border-radius: 30px;
  transition: all 0.3s;
  font-size: 14px;
  color: #666;
}

.role-btn.active {
  background-color: #409eff;
  color: white;
}

.login-form {
  .el-form-item {
    margin-bottom: 25px;
  }

  :deep(.el-input__wrapper) {
    background-color: #f8faff;
    border-radius: 4px;
    box-shadow: none;
  }

  :deep(.el-input__inner) {
    height: 40px;
  }
}

/* 验证码样式 */
.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-img {
  margin-left: 10px;
  height: 40px;
  width: 120px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.login-button {
  width: 100%;
  height: 40px;
  border-radius: 20px;
  font-size: 16px;
  background: linear-gradient(90deg, #1e90ff, #4169e1);
  border: none;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
  color: #999;
  font-size: 12px;
}

.bottom-border {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 1px;
  background-color: #6495ed;
  z-index: 3;
}

/* 响应式布局 */
@media screen and (max-width: 992px) {
  .login-content {
    flex-direction: column;
    width: 90%;
  }

  .login-left {
    display: none;
  }

  .login-form-box {
    width: 100%;
    max-width: 400px;
  }
}
</style>
